package net.asgarli.abalone.model;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UnitPreviews implements Marshallable {
    private static final long serialVersionUID = 1L;

    private List<UnitPreview> unitPreviews = new ArrayList<UnitPreview>();

    @Override
    public byte[] writeToBytes() throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);

        for (UnitPreview up : unitPreviews) {
            byte[] upInBytes = up.writeToBytes();
            dos.writeInt(upInBytes.length);
            dos.write(upInBytes);
        }

        return bos.toByteArray();
    }

    @Override
    public void restoreFromBytes(byte[] bytes) throws IOException {
        DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));

        unitPreviews.clear();
        while (in.available() > 0) {
            int size = in.readInt();
            byte[] upInByte = new byte[size];
            in.read(upInByte);
            UnitPreview up = new UnitPreview();
            up.restoreFromBytes(upInByte);

            unitPreviews.add(up);
        }

    }

    //
    // ************************* GENERATED *************************
    // ************************* Getters and Setters ***************
    //
    public List<UnitPreview> getUnitPreviews() {
        return unitPreviews;
    }

    public void setUnitPreviews(List<UnitPreview> unitPreviews) {
        this.unitPreviews = unitPreviews;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((unitPreviews == null) ? 0 : unitPreviews.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        UnitPreviews other = (UnitPreviews) obj;
        if (unitPreviews == null) {
            if (other.unitPreviews != null) return false;
        } else if (!unitPreviews.equals(other.unitPreviews)) return false;
        return true;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("UnitPreviews [unitPreviews=");
        builder.append(unitPreviews);
        builder.append("]");
        return builder.toString();
    }
}
